<template>
  <j-modal
    :title="title"
    :width="800"
    :visible="visible"
    :maskClosable="false"
    :ok-button-props="{ props: { disabled: disableSubmit } }"
    :fullscreen="true"
    ok-text="提交审批"
    @close="close"
    cancelText="关闭"
  >
    <template slot="footer">
      <a-button key="back" style="padding-left: 8px; padding-right: 8px" @click="close(false)"> 关闭 </a-button>
      <a-popconfirm :disabled="disableSubmit" title="确定保存吗?" @confirm="() => savePlan()">
        <a-button key="save" style="padding-left: 8px; padding-right: 8px" :disabled="disableSubmit"> 保存 </a-button>
      </a-popconfirm>
      <a-button
        key="submit"
        type="primary"
        style="padding-left: 8px; padding-right: 8px"
        :disabled="disableSubmit"
        @click="close(true)"
      >
        提交审批
      </a-button>
    </template>
    <div style="margin: 0 auto" :class="{ isCheck: isCheck }">
      <a-form-model ref="form" :rules="validatorRules" :model="model">
        <table class="table table-striped table-bordered" align="center" valign="center">
          <tr>
            <td class="column title" colspan="12">基本信息</td>
          </tr>
          <tr>
            <td class="column">计划编号</td>
            <td class="value">
              <a-input v-model="model.number" placeholder="系统生成" :disabled="true"></a-input>
            </td>
            <td class="column item-required">计划年度</td>
            <td class="value">
              <a-form-model-item label="" prop="planYear">
                <a-date-picker
                  mode="year"
                  placeholder="请选择年份"
                  format="YYYY"
                  value-format="yyyy-MM-dd"
                  v-model="model.planYear"
                  :open="yearPickShow"
                  :disabled="disableTitle"
                  style="width: 100%"
                  @panelChange="handlePanelChange"
                  @openChange="handleOpenChange"
                />
              </a-form-model-item>
            </td>
            <td class="column item-required">计划名称</td>
            <td class="value">
              <a-form-model-item label="" prop="name">
                <a-input v-model="model.name" :disabled="disableTitle"></a-input>
              </a-form-model-item>
            </td>
            <td class="column item-required">计划负责人</td>
            <td class="value">
              <a-form-model-item v-if="!disableSubmit" label="" prop="principal">
                <a-select v-model="model.principal" :disabled='disableSubmit'>
                  <a-select-option v-for='(item,index) in principalData' :key='item.id' :value="item.userId">
                    {{ item.userName }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
              <a-input v-else v-model="model.principalText" :disabled="true"></a-input>
            </td>
          </tr>
          <tr>
            <td class="column">审计单位</td>
            <td class="value" colspan="7">
              <a-form-model-item label="" prop="remidText">
                <a-input
                  v-if="organShow"
                  @click.native="openOrganModel"
                  v-model="model.remidText"
                  :disabled="true"
                ></a-input>
              </a-form-model-item>
            </td>
          </tr>
          <tr>
            <td class="column item-required" colspan="1">年度审计工作目标</td>
            <td class="value" colspan="7">
              <a-form-model-item label="" prop="aims">
                <a-input v-model="model.aims" :disabled="disableSubmit"></a-input>
              </a-form-model-item>
            </td>
          </tr>
          <tr>
            <td class="column" colspan="12">审计项目计划明细</td>
          </tr>
          <tr>
            <td class="value" colspan="12" style="padding: 0">
              <a-table
                class="edit-list"
                size="middle"
                bordered
                :columns="columns1"
                :dataSource="dataSource1"
                :pagination="ipagination1"
              >
                <span slot="actionName">
                  <a-button
                    v-if="!disableSubmit"
                    style="padding: 0 7px"
                    size="small"
                    @click="addPlanList('年度审计计划制定-新增')"
                    type="primary"
                    icon="plus"
                    >{{ addList }}</a-button
                  >
                  {{ disableSubmit ? '操作' : '' }}
                </span>
                <span v-if="enterStatus != '1'" slot="action" slot-scope="text, record">
                  <a @click="handleCheck(record, '计划明细-查看')">查看</a>
                  <a-divider style="margin: 0 8px" type="vertical" />
                  <a-dropdown>
                    <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                    <a-menu slot="overlay">
                      <a-menu-item v-if="model.status == '1' || model.status == '4' || model.status == null || (model.status == '5' && record.operating == '3')">
                        <a style="text-align: center" @click="handleEdit(record, '计划明细-编辑')">编辑</a>
                      </a-menu-item>
                      <a-menu-item v-if="model.status == '1' || model.status == '4' || model.status == null">
                        <a-popconfirm title="确定删除吗?" @confirm="() => changeDelete(record.id)">
                          <a style="text-align: center">删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                      <a-menu-item v-if="model.status == '3'">
                        <a-popconfirm title="确定调减吗?" @confirm="() => addOrCut(record.id, '2')">
                          <a style="text-align: center">调减</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </span>
              </a-table>
            </td>
          </tr>
          <tr v-if="model.status == '3' || model.upstate == '3'">
            <td class="column" colspan="12">调整</td>
          </tr>
          <tr v-if="model.status == '3' || model.upstate == '3'">
            <td class="value" colspan="12" style="padding: 0">
              <a-table
                class="edit-list"
                size="middle"
                bordered
                :columns="columns2"
                :dataSource="dataSource2"
                :pagination="ipagination2"
                :scroll="{ x: 200, y: 240 }"
              >
                <span v-if="enterStatus != '1'" slot="action" slot-scope="text, record">
                  <a @click="handleCheck(record, '年度审计计划制定-查看')">查看</a>
                  <a-divider style="margin: 0 8px" type="vertical" />
                  <a-dropdown>
                    <a class="ant-dropdown-link">更多 <a-icon type="down" /></a>
                    <a-menu slot="overlay">
                      <a-menu-item v-if="record.operating == '1'">
                        <a style="text-align: center" @click="handleEdit(record, '年度审计计划制定-编辑')">编辑</a>
                      </a-menu-item>
                      <a-menu-item v-if="record.operating == '2'">
                        <a style="text-align: center" @click="addOrCut(record.id, '0')">恢复</a>
                      </a-menu-item>
                      <a-menu-item v-if="record.operating == '1'">
                        <a-popconfirm title="确定删除吗?" @confirm="() => changeDelete(record.id)">
                          <a style="text-align: center">删除</a>
                        </a-popconfirm>
                      </a-menu-item>
                    </a-menu>
                  </a-dropdown>
                </span>
              </a-table>
            </td>
          </tr>
          <tr>
            <td class="column" colspan="12">审核记录</td>
          </tr>
          <tr>
            <td class="value" colspan="12" style="padding: 0">
              <a-table
                class="edit-list"
                size="middle"
                bordered
                :columns="columns3"
                :dataSource="dataSource3"
                :pagination="ipagination3"
                :scroll="{ x: 200, y: 240 }"
              >
              </a-table>
            </td>
          </tr>
        </table>
      </a-form-model>
    </div>
    <!-- table区域-end -->
    <OrganModal ref="departModal" @ok="updateQueryParam"></OrganModal>
    <PlanDetails ref="modalForm" :status="model.status" @ok="savePlanSuccess"></PlanDetails>
    <SelectApprove ref="approver" @submitData="submitData"></SelectApprove>
  </j-modal>
</template>
<script>
import { deleteAction, getAction, httpAction } from '@/api/manage'
import OrganModal from '../../components/OrganModal'
import SelectApprove from '../publicModel/SelectApprover'
import PlanDetails from './PlanDetails'
import moment from 'moment'
import columns1 from './columns1'
import columns2 from './columns2'
import columns3 from './columns3'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import store from '@/store/'

export default {
  name: 'NdsjjhzdModal',
  mixins: [JeecgListMixin],
  components: {
    OrganModal,
    PlanDetails,
    SelectApprove,
  },
  data() {
    return {
      enterStatus: '0',
      addList: '新增',
      disableSubmit: false,
      disableTitle: false,
      title: '机构信息',
      visible: false,
      isCheck: false,
      url: {
        get: '/sjzyzhgl/sjPlanInfo/planInfoList',
        add: '/sjzyzhgl/sjResourceAuditors/add',
        edit: '/sjzyzhgl/sjResourceAuditors/edit',
        list: '/sjzyzhgl/sjPlanProjectInfo/projectInfoByProId',
        approveList: '/sjzyzhgl/sjApplyLog/queryApplyLogListByPId', //审批记录列表
        submitData: '/common/sjProcCommon/subShen',
        secondSubmit: '/common/sjProcCommon/doapply',
        addTitle: '/sjzyzhgl/sjPlanInfo/addReturnId',
        updataTitle: '/sjzyzhgl/sjPlanInfo/edit',
        addOrCut: '/sjzyzhgl/sjPlanProjectInfo/edit',
        delete: '/sjzyzhgl/sjPlanProjectInfo/delete',
        queryPlanUserInfo:'/sjzyzhgl/sjPlanInfo/queryPlanUserInfo',
      },
      organShow: true,
      model: {},
      yearPickShow: false,
      columns1: columns1(this),
      columns2: columns2(this),
      columns3: columns3(this),
      dataSource1: [],
      dataSource2: [],
      dataSource3: [],
      ipagination1: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        onChange: (pageNumber) => {
          this.onChange1(pageNumber)
        },
        showQuickJumper: true,
        total: 0,
      },
      ipagination2: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        onChange: (pageNumber) => {
          this.onChange2(pageNumber)
        },
        showQuickJumper: true,
        total: 0,
      },
      ipagination3: {
        current: 1,
        pageSize: 10,
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
        onChange: (pageNumber) => {
          this.onChange3(pageNumber)
        },
        showQuickJumper: true,
        total: 0,
      },
      approverId: '',
      validatorRules: {
        principal: [{ required: true, message: '请选择!' }],
        planYear: [{ required: true, message: '请选择!' }],
        name: [{ required: true, message: '请选择!' }],
        remidText: [{ required: true, message: '请选择!' }],
        aims: [{ required: true, message: '请选择!' }],
      },
      principalData:[],
    }
  },
  mounted() {},
  methods: {
    add() {
      this.queryPlanUserInfo(null, (result) => {
        this.model = {
          principal: result[0].userId,
          remidText: store.getters.departInfo.departName,
          remid: store.getters.departInfo.id,
          planYear: '',
          status: null
        }
        this.disableTitle = false
        this.dataSource1 = []
        this.dataSource2 = []
        this.dataSource3 = []
        this.visible = true
        this.addList = '新增'
        this.enterStatus = '0'
      })
    },
    check(record) {
      this.model = Object.assign({}, record)
      this.disableTitle = true
      this.visible = true
      this.enterStatus = '1'
      this.httpRequest()
      this.list1()
      this.list2()
      this.list3()
    },
    edit(record) {
      this.queryPlanUserInfo(record.createBy, (result) => {
        this.model = Object.assign({}, record)
        this.visible = true
        if (this.model.status == '1' || this.model.status == '4') {
          this.disableTitle = false
        } else {
          this.disableTitle = true
        }
        if (this.model.status == '3') {
          this.addList = '调增'
        } else {
          this.addList = '新增'
        }
        this.enterStatus = '2'
        this.httpRequest()
        this.list1()
        this.list2()
        this.list3()
      })
    },

    queryPlanUserInfo(userId, callBack) {
      getAction(this.url.queryPlanUserInfo, { userId: userId })
        .then((res) => {
          if (res.success && res.result) {
            if (res.result && res.result.length > 0) {
              this.principalData = res.result
              callBack(res.result)
            } else {
              this.$message.error('未设置审计部部长，请联系本单位审计负责人')
            }
          } else {
            this.$message.error('获取审计部部长异常，请联系本单位审计负责人')
          }
        })
        .finally(() => {
        })
    },

    // 获取计划头部信息
    httpRequest() {
      getAction(this.url.get, { id: this.model.id })
        .then((res) => {
          if (res.success && res.result) {
            this.model = res.result.records[0]
          } else {
            console.log(res)
          }
        })
        .finally(() => {})
    },
    // 点击关闭或提交审核
    close(isSubmit) {
      if (isSubmit) {
        //点击提交审批
        if (!this.model.id) {
          this.$message.error('请先保存')
          return
        }
        this.$refs.approver.showApproveConfirm = true
      } else {
        this.visible = false
      }
    },
    // 提交审核
    submitData(id) {
      let httpurl = this.url.submitData
      let param = {
        proId: this.model.id,
        userIds: id,
        type: '1',
      }
      if (this.model.status == '3') {
        httpurl = this.url.secondSubmit
      } else {
        param.type = '1'
      }
      getAction(httpurl, param).then((res) => {
        if (res.success && res.result) {
          this.$message.success('审批已启动成功')
          this.visible = false
          this.$emit('ok')
        } else {
        }
      })
    },
    // 保存计划
    saveData() {
      let httpurl, method
      if (!this.model.id) {
        httpurl = this.url.addTitle
        method = 'post'
      } else {
        httpurl = this.url.updataTitle
        method = 'put'
      }
      return new Promise((resolve, reject) => {
        httpAction(httpurl, {type: '1', ...this.model}, method)
          .then((res) => {
            if (res.success) {
              if (!this.model.id) {
                this.model.id = res.result
              }
              resolve(res.success)
            } else {
              reject(res.success)
              this.$message.error(res.message)
            }
          })
          .finally(() => {})
      })
    },
    savePlan() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveData().then((data) => {
            if (data) {
              this.$message.success('草案保存成功')
              this.$emit('ok')
              this.visible = false
            }
          })
        } else {
          return false
        }
      })
    },
    // 新增或调增计划项目
    addPlanList(name) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.saveData().then((data) => {
            if (data) {
              this.$refs.modalForm.proId = this.model.id
              this.$refs.modalForm.title = name
              this.$refs.modalForm.submitState = this.model.status
              this.$refs.modalForm.secondState = this.model.upstate
              this.$refs.modalForm.disableSubmit = false
              this.$refs.modalForm.add()
            }
          })
        } else {
          return false
        }
      })
    },
    // 调减或恢复计划项目
    addOrCut(id, status) {
      if (!this.url.addOrCut) {
        this.$message.error('请设置url.addOrCut!')
        return
      }
      var that = this
      httpAction(that.url.addOrCut, { id: id, operating: status }, 'put').then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.$message.success(res.message)
          this.list1()
          this.list2()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    // 删除计划项目
    changeDelete: function (id) {
      if (!this.url.delete) {
        this.$message.error('请设置url.delete属性!')
        return
      }
      var that = this
      deleteAction(that.url.delete, { id: id }).then((res) => {
        if (res.success) {
          //重新计算分页问题
          that.reCalculatePage(1)
          that.$message.success(res.message)
          this.list1()
          this.list2()
        } else {
          that.$message.warning(res.message)
        }
      })
    },
    // 机构列表弹窗
    openOrganModel() {
      this.$refs.departModal.show()
      this.$refs.departModal.selectedKeys = [this.model.remid]
    },
    // 确认选中机构
    updateQueryParam(data) {
      this.model.remidText = data.departName
      this.model.remid = data.id
      this.organShow = false
      this.$nextTick(() => {
        this.organShow = true
      })
    },
    list1() {
      getAction(this.url.list, {
        proId: this.model.id,
        pageSize: this.ipagination1.pageSize,
        pageNo: this.ipagination1.current,
        operationFlag: 'normal',
      }).then((res) => {
        if (res.success && res.result) {
          this.dataSource1 = res.result.records
          this.ipagination1.total = res.result.total
        } else {
          this.ipagination1.total = 0
        }
      })
    },
    list2() {
      getAction(this.url.list, {
        proId: this.model.id,
        pageSize: this.ipagination1.pageSize,
        pageNo: this.ipagination1.current,
        operationFlag: 'adjust',
      }).then((res) => {
        if (res.success && res.result) {
          this.dataSource2 = res.result.records
          this.ipagination2.total = res.result.total
        } else {
          this.ipagination2.total = 0
        }
      })
    },
    list3() {
      getAction(this.url.approveList, {
        pid: this.model.id,
        pageSize: this.ipagination3.pageSize,
        pageNo: this.ipagination3.current,
      }).then((res) => {
        if (res.success && res.result) {
          this.dataSource3 = res.result.records
          this.ipagination3.total = res.result.total
        } else {
          this.ipagination3.total = 0
        }
      })
    },
    // 分页
    onChange1(pageNumber) {
      this.ipagination1.current = pageNumber
      this.list1()
    },
    onChange2(pageNumber) {
      this.ipagination2.current = pageNumber
      this.list2()
    },
    onChange3(pageNumber) {
      this.ipagination3.current = pageNumber
      this.list3()
    },
    // 弹出日历和关闭日历的回调
    handleOpenChange(status) {
      this.yearPickShow = status
    },
    moment,
    // 得到年份选择器的值
    handlePanelChange(value) {
      this.model.planYear = moment(value).format('YYYY')
      this.yearPickShow = false
      this.$refs.form.validateField('planYear', (error) => {
        console.log(error)
      })
    },
    // 计划项目新增成功
    savePlanSuccess() {
      this.list1()
      this.list2()
      this.list3()
    },
  },
}
</script>

<style lang='less' scoped>
@import '../../css/checkAndEdit.less';
/deep/ .ant-table-hide-scrollbar {
  scrollbar-color: unset !important;
  margin-bottom: -10px !important;
}
</style>
